﻿using System.Collections.Generic;
using System.Threading;
using System.Diagnostics;

namespace Z2.Core
{
    public class ParallelManager
    {
        private readonly List<ManualResetEvent> _events = new List<ManualResetEvent>();

        public void Create(ParallelActionInvoker invoker)
        {
			Debug.WriteLine(string.Format("Creating parallel operation.. #{0}", _events.Count + 1));
            ParallelOperation operation = new ParallelOperation(invoker);
            _events.Add(operation.DoneEvent);
            ThreadPool.QueueUserWorkItem(operation.ThreadPoolCallback, null);
        }

        public void Wait()
        {
			Debug.WriteLine("Waiting for all operations..");
            if(_events.Count == 0) return;
            WaitHandle.WaitAll(_events.ToArray());
            _events.Clear();
			Debug.WriteLine("Done.");
        }

    }
}
